<?php
namespace Common\Model\Counter;
use Think\Model;
/**
 * Created by IntelliJ IDEA.
 * User: fanxu(746439274@qq.com)
 * Date: 15/7/7
 * Time: 上午2:51
 */

class Builder extends Model{

    /**
     * 表名称
     */
    protected $tableName = 'counter';

    protected $_dbNum = 'common';

    /**
     * 单例对象
     * @var Builder
     */
    public static $singletonObjects = null;

    /**
     * 根据key返回唯一的id
     * @param       string  $key    键
     * @return      int
     */
    public function getUniqueIdByKey( $key )
    {
        //数据库自增长 预留其他自增长方式
        return $this->_incrementBySelf( $key );
    }

    /**
     * 获取单例
     * @return Builder
     */
    public static function getInstance()
    {
        if( self::$singletonObjects == null )
        {
            self::$singletonObjects = new self;
        }

        return self::$singletonObjects;
    }

    /**
     * 自己实现递增
     * @param       string  $key    键
     * @return      int
     */
    private function _incrementBySelf( $key )
    {
        $this->startTrans();
        $map['key']=$key;
        $value = $this->where( $map )->getField('value');
        //如果没有设置过
        if( !$value ){
            $value = time();
            $result = $this->add( ['key'=>$key,'value'=>$value] );
        }
        else{
            ++$value;
            $result = $this->where( $map )->setField( 'value' , $value );
        }
        if( !$result ){
            $this->rollback();
            E('操作失败!');
        }
        $this->commit();
        return $value;
    }
}